package com.hcj.shiro;

/**
 * @Author: HuangChangjin 2017-10-27 19:50
 * @Description:
 */
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 防止密码被暴力破解
 */
public class RetryLimitHashedCredentialsMatcher extends  HashedCredentialsMatcher {
    private static  final Logger logger =  LoggerFactory.getLogger(RetryLimitHashedCredentialsMatcher.class);
    private Cache<String, AtomicInteger> passwordRetryCache;

    public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
        logger.info("防止密码被暴力破解开始，缓存：{}",passwordRetryCache.toString());

    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token,AuthenticationInfo info) {
        logger.info("doCredentialsMatch===start==，缓存：{}",passwordRetryCache.toString());
        String username = (String) token.getPrincipal();
        // retry count + 1
        AtomicInteger retryCount = passwordRetryCache.get(username);

        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }
        if (retryCount.incrementAndGet() > 5) {
            // if retry count > 5 throw
            logger.warn("username: " + username + " tried to login more than 5 times in period");
            throw new ExcessiveAttemptsException("username: " + username + " tried to login more than 5 times in period");
        }

        boolean matches = super.doCredentialsMatch(token, info);
        if (matches) {
            // clear retry count
            passwordRetryCache.remove(username);
        }else {
            int lastChance = 5 - retryCount.get();
            throw  new AccountException("密码错误，您还剩["+ lastChance +"]次机会");
        }
        return matches;
    }
}
